<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学号" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input
          v-model="queryParams.age"
          placeholder="请输入年龄"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="就读学校" prop="school">
        <el-input
          v-model="queryParams.school"
          placeholder="请输入就读学校"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:student:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:student:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:student:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:student:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="学号" align="center" prop="id" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="出生时间" align="center" prop="birthday" >
        <template slot-scope="scope">
          <span>{{parseTime(scope.row.birthday, '{y}-{m}-{d}')}}</span>
        </template>
        </el-table-column>


        <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>

      <el-table-column label="就读学校" align="center" prop="school" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:student:edit']"
          >修改(更多)</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:student:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
:value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生时间" prop="birthday">
          <el-date-picker clearable
                          v-model="form.birthday"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="就读学校" prop="school">
          <el-input v-model="form.school" placeholder="请输入就读学校" />
        </el-form-item>
<el-row>
        <el-col v-for="(item, index) in contactArray" :key="index" :span="24" style="text-align: left;">
          <el-form-item label="联系人:">
            <el-select
              v-model="contactArray[index].contactRelation"
              filterable
              placeholder="关系"
              default-first-option
              style="width: 80px"
            >
              <el-option
                v-for="dict in contactRelationOptions"
                :key="dict.id"
                :label="dict.dictLabel"
                :value="dict.dictLabel"
              />
            </el-select>
            <el-input v-model="contactArray[index].contactNick" style="width: 100px;" placeholder="称呼" />
            <el-input v-model="contactArray[index].contactPhone" style="width: 150px;" placeholder="联系电话" />
            <el-button v-if="index === 0 && contactArray.length > 0" style="padding: 3px 5px;margin-left: 5px;" type="primary" icon="el-icon-plus" size="mini" @click="handleAddContactInfo()" />
            <el-button v-if="index > 0" style="padding: 3px 5px;margin-left: 5px;" type="danger" icon="el-icon-minus" size="mini" @click="handleDeleteContactInfo(index)" />
          </el-form-item>
        </el-col>
</el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudent, getStudent, delStudent, addStudent, updateStudent } from "@/api/system/student";

export default {
  name: "Student",
  dicts: ['sys_user_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生表表格数据
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        id: null,
        age: null,
        sex: null,
        school: null,
      },
      contactRelationOptions: [{id:1,dictLabel:"爸爸"}, {id:2,dictLabel:"妈妈"}, {id:3,dictLabel:"叔叔"},
        {id:4,dictLabel:"哥哥"}, {id:5,dictLabel:"姐姐"}, {id:6,dictLabel:"阿姨"}, {id:7,dictLabel:"其他"}],

      // 联系人
      contactArray: [{
        contactRelation: '',
        contactNick: '',
        contactPhone: ''
      }],
          // 表单参数
      form: {

      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        age: [

          { required: true, message: '年龄不能为空', trigger: 'blur' },
          // {
          //   pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
          //   message: '请输入正确的手机号码',
          //   trigger: 'blur'
          // }

        ],

      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学生表列表 */
    getList() {
      this.loading = true;
      listStudent(this.queryParams).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: null,
        id: null,
        age: null,
        sex: null,
        school: null,
        remark: null,
        birthday: null

      };
      this.contactArray=[{
        contactRelation: '',
        contactNick: '',
        contactPhone: ''
      }];

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStudent(id).then(response => {
        this.form = response.data;
        if (response.data.contactList && response.data.contactList.length > 0) {
          this.contactArray = response.data.contactList
        }
        this.open = true;
        this.title = "修改学生表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      const pattern = /^1[3456789]\d{9}$/;
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.contactArray.forEach(item => {
            if (item.contactRelation === undefined || item.contactRelation === null || item.contactRelation.trim() === '') {
              this.msgError('请选择联系人与学生关系')
              valid = false
            } else if (item.contactPhone === undefined || item.contactPhone === null || item.contactPhone.trim() === '') {
              this.msgError('请填写联系人电话')
              valid = false
            }
            else if( !pattern.test(item.contactPhone)){
              this.msgError('联系人电话格式错误')
              valid = false

            }
          })
          if(valid){
          this.form.contactList = this.contactArray
          if (this.form.id != null) {
            updateStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // 联系人
              this.contactArray=[{
                contactRelation: '',
                contactNick: '',
                contactPhone: ''
              }];
            });
          }
        }}
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const name =row.name||''
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学生名为"' + name + '"的数据项？').then(function() {
        return delStudent(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/student/export', {
        ...this.queryParams
      }, `student_${new Date().getTime()}.xlsx`)
    },
    // 增加联系人
    handleAddContactInfo() {
      this.$set(this.contactArray, this.contactArray.length, {
        contactRelation: '',
        contactNick: '',
        contactPhone: ''
      })
    },
    // 删除联系人
    handleDeleteContactInfo(index) {
      this.contactArray.splice(index, 1)
    }
  }
};
</script>
